import {getLocal} from "../../utils/local";

export async function delete_shopcart(item) {
    var todo = AV.Object.createWithoutData('shopcartItem', item.objectId);
    var delete_result = await todo.destroy().catch(e => console.error(e));
    return delete_result
}

export async function make_order(shopcartItems) {
    var OrderObJECT = AV.Object.extend('order');
    var user = AV.Object.createWithoutData('user', getLocal('app.login_user').objectId);
    // save order
    var orderObJECT = new OrderObJECT();
    var totalPrice = 0;
    var numberCount = 0
    shopcartItems.map(item => {
        numberCount++;
        totalPrice += item.unitPrice * item.quantity
    })
    orderObJECT.set('user', user);
    orderObJECT.set('totalPrice', totalPrice);
    orderObJECT.set('numberCount', numberCount);
    orderObJECT.set('status', "已付款");
    var orderObJECT_result = await  orderObJECT.save()
    //save orderItem
    var orderItems = []
    shopcartItems.map(item => {
        var OrderItem = AV.Object.extend('orderItem');
        var orderItem = new OrderItem()
        orderItem.set("quantity", item.quantity)
        orderItem.set("unitPrice", item.unitPrice)
        orderItem.set("fabric", AV.Object.createWithoutData('fabric', item.fabric.objectId))
        orderItem.set("design", AV.Object.createWithoutData('design', item.design.objectId))
        orderItem.set("order", orderObJECT_result)
        orderItems.push(orderItem)


    })
    var result = await   AV.Object.saveAll(orderItems).then(res => res.map(item => item.toJSON()))
    for (var i = 0; i < result.length; i++) {
        var order = result[i]
        //记录orderCount  1.查询 2修改
        var query = new AV.Query('salesCount');
        query.equalTo('design', AV.Object.createWithoutData('design', order.design.objectId))
        var orderCount = (await query.find())[0];

        var OrderCountObject = AV.Object.extend('salesCount');
        var orderCountObject = new OrderCountObject();

        /*存在 add*/
        if (orderCount) {
            orderCountObject.id = orderCount.getObjectId()
            orderCountObject.set("count", orderCount.toJSON().count + order.quantity)
            await orderCountObject.save()
        } else {
            orderCountObject.set("design", AV.Object.createWithoutData('design', order.design.objectId))
            orderCountObject.set("count", order.quantity)
            await orderCountObject.save()
        }
    }


    //DELETE shopcartitems
    var shopcartitems_object = []
    shopcartItems.map(item => {
        var ShopcartItem = AV.Object.extend('shopcartItem');
        var shopcartitem = new ShopcartItem()
        shopcartitem.id = item.objectId
        shopcartitems_object.push(shopcartitem)
    })
    await AV.Object.destroyAll(shopcartitems_object)


    return {order: orderObJECT_result.toJSON(), orders: result}
}